package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service

public class ApUserLoginServiceImpl implements ApUserLoginService {




    @Autowired
    private ApUserMapper apUserMapper;



    /**
     * app端用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        String password = dto.getPassword();
        String phone = dto.getPhone();
        Integer equipmentId = dto.getEquipmentId();
        //判断参数
        if (equipmentId == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //查询登录的用户
        if (StringUtils.isNotBlank(password) && StringUtils.isNotBlank(phone) ){
            //表示用户登录
            //根据手机号查询用户信息
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
            }
            //加密密码 看和数据库中的密码是否一致
            String newPsw = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes(StandardCharsets.UTF_8));
            if (!newPsw.equals(apUser.getPassword())){
                //密码不正确
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //创建token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //消除用户对象中的敏感信息
            apUser.setPassword("");
            apUser.setPhone("");
            //创建map返回前端
            Map map = new HashMap();
            map.put("token",token);
            map.put("user",apUser);

            //返回数据
            return ResponseResult.okResult(map);

        }else {
            //表示用户没有登录  未登录查看 用设备id
            //直接办法token  id的值为0
            Map map = new HashMap();
            map.put("token" , AppJwtUtil.getToken(0L));
            //返回前段
            return ResponseResult.okResult(map);
        }
    }
}
